<?php
/**
* $Id: tv_Mailer.php 2942 2012-02-20 10:48:18Z huong.pham $
*/
class tv_loader extends CI_Loader{
    function widget($name, $params = null, $return = FALSE){
        $widgetClass = ucfirst($name) . 'Widget';
        # start buffering output
        ob_start();
        include_once(APPPATH . '/widgets/' . $widgetClass . '.php');
        $widget = new $widgetClass;
        $widget->init($params);
        $widget->run();
        if ($return == TRUE) # do not print our output
        {
            $buffer = ob_get_contents();
            @ob_end_clean();
            return $buffer;
        }
        else # print out output
        {
            @ob_end_flush();
        }
    }

}
class TV_Mailer {  
    /**
    * Send email 
    * 
    * @param array $info
    * @return mixed
    */
    function sendMail($info)
    {
        //Load mail library
        require_once(APPPATH.'libraries/PhpMail.php');
        $mailer = new PHPMail();
        $mailer->setup($info['config']);
        //Load mail template
        $template = QS_Mailer::loadMailTemplate('email_templates', $info['template']);
       //send mail parameters
        
        $body = QS_Mailer::parseMailContent($info['mailInfo'], $template); 
        
        return $mailer->send($info['subject'], $body, '', $info['to'] , $info['from']);  
    }
    /**
    * Load template email
    * 
    * @param string $resourceFolder
    * @param string $mailTemplate
    * @return string
    */
    function loadMailTemplate($resourceFolder, $mailTemplate)
    {
        $filename = $_SERVER['DOCUMENT_ROOT'].'/'.$resourceFolder.'/'.$mailTemplate;  
        if($fp = fopen($filename, 'rb')) {
            $return = fread($fp, filesize($filename));
            fclose($fp);
            return $return;
        } else {
            return '';
        }
    }
    /**
    * Parse Mail Content
    * 
    * @param object $obj
    * @param string $template
    * @return string
    */
    function parseMailContent($obj, $template)
    {                                              
        $matches = array('');
        while(count($matches) > 0)
        {
            preg_match("/\[([a-zA-Z0-9])*\]/", $template, $matches);
            if(empty($matches))
            {
                break;
            }
            $tag = $matches[0];
            $property = substr($tag, 1, strlen($tag)-2);
            if ($property != '') 
            {
                $value = $obj->$property;
                $template = str_replace($tag, $value, $template);
            }
        } // while
        return $template;
    } 
}  
?>
